package com.alfy.sbdemo.websocketdemo.demo2;

import javax.websocket.*;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import java.util.Map;

public class MyAuthWebSocketClient {

    private Session session;

    public static class MyClientEndpoint extends Endpoint{

        @Override
        public void onOpen(Session session, EndpointConfig config) {
            System.out.println("链接成功.......");
        }

    }

    public void connect() throws Exception {
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        ClientEndpointConfig config = ClientEndpointConfig.Builder.create().configurator(new ClientEndpointConfig.Configurator() {

            @Override
            public void beforeRequest(Map<String, List<String>> headers) {
                // 添加认证信息
                headers.put("Authorization", Collections.singletonList("valid-token"));
            }

        }).build();
        container.connectToServer(new MyClientEndpoint(), config, new URI("ws://localhost:8889/websocket/server3?token=valid-token"));
    }

}
